package com.youkeyi.ddy.cloud.application.applet.crm.order.controller;

import com.youkeyi.ddy.cloud.application.applet.support.service.UserSupportService;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.AppletCustomerOrderCloudService;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.dto.AppletCustomerOrderDetailCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.dto.AppletCustomerOrderListCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.dto.AppletCustomerOrderListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.param.AppletCustomerOrderCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.param.AppletCustomerOrderListCloudParam;
import com.youkeyi.ddy.cloud.common.api.application.applet.crm.order.param.AppletCustomerOrderUpdateCloudParam;
import com.youkeyi.ddy.cloud.common.api.application.system.user.dto.SystemUserListByOrgCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.user.dto.SystemUserListByOrgItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.user.param.SystemUserListByOrgCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.customer.CrmCustomerCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.crm.customer.dto.CrmCustomerListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.crm.customer.dto.CrmCustomerListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.crm.customer.param.CrmCustomerQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.order.CrmCustomerOrderCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.crm.order.dto.CrmCustomerOrderListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.crm.order.dto.CrmCustomerOrderListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.crm.order.param.CrmCustomerOrderCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.order.param.CrmCustomerOrderQueryCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.crm.order.param.CrmCustomerOrderUpdateCloudParam;
import com.youkeyi.ddy.cloud.common.constant.YoukeyiDdyCloudBasicCrmConstant;
import com.youkeyi.ddy.cloud.common.context.YoukeyiSystemContext;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * AppletCustomerOrderController
 *
 * @Author liuxiawang
 * @Date 2024/3/4 5:45 PM
 * @Location shenzhen.china
 */
@Service
public class AppletCustomerOrderController implements AppletCustomerOrderCloudService {
    
    @Autowired
    private CrmCustomerOrderCloudService crmCustomerOrderCloudService;
    @Autowired
    private CrmCustomerCloudService crmCustomerCloudService;
    @Autowired
    private UserSupportService userSupportService;

    @Override
    public AppletCustomerOrderListCloudDto list(AppletCustomerOrderListCloudParam param) {
        AppletCustomerOrderListCloudDto dto = new AppletCustomerOrderListCloudDto();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        String positionCode = YoukeyiSystemContext.getPositionCode();
        String organizationKey = YoukeyiSystemContext.getOrganizationKey();
        String currentUserKey = YoukeyiSystemContext.getUserPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            dto.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return dto;
        }
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }
        CrmCustomerOrderQueryCloudParam customerOrderQueryCloudParam = new CrmCustomerOrderQueryCloudParam();



        // 判断当前登陆人是主管、副主管还是普通成员，做数据权限隔离
        if (StringUtils.isBlank(positionCode)) {
            dto.setErrorMessage(ResponseCodeEnum.SYSTEM_UNKNOWN_POSITION_CODE_ERROR.getMessage());
            return dto;
        }
        // 主管副主管
        if (positionCode.endsWith("-ZG") || positionCode.endsWith("-FZG")) {
            // 查询他的组织下属人员的
            List<String> userKeys = new ArrayList<>();
            if (StringUtils.isNotBlank(organizationKey)) {
                SystemUserListByOrgCloudParam userListByOrgCloudParam = new SystemUserListByOrgCloudParam();
                userListByOrgCloudParam.setOrganizationPrimaryKeys(Collections.singletonList(organizationKey));
                SystemUserListByOrgCloudDto userDtos = userSupportService.listUserByOrg(userListByOrgCloudParam);
                if (null != userDtos && CollectionUtils.isNotEmpty(userDtos.getRows())) {
                    userKeys.addAll(userDtos.getRows().stream().map(SystemUserListByOrgItemCloudDto::getUserPrimaryKey).collect(Collectors.toList()));
                }
            }
            if (CollectionUtils.isEmpty(userKeys)) {
                dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
                return dto;
            }

            // 查询出来的下属用户key
            customerOrderQueryCloudParam.setCorpKeys(Collections.singletonList(corpKey));
            customerOrderQueryCloudParam.setPublicUserKeys(userKeys);
        }
        // 普通成员
        else if (positionCode.endsWith("-CY")) {
            customerOrderQueryCloudParam.setCorpKeys(Collections.singletonList(corpKey));
            customerOrderQueryCloudParam.setSourceUserKey(currentUserKey);
        }
        // 超管
        else if (positionCode.equals("superadmin")) {
            // 超级管理员不需要增加什么过滤
        }
        // 管理员
        else if (positionCode.equals("-admin")) {
            // 管理员看主体的
            customerOrderQueryCloudParam.setCorpKeys(Collections.singletonList(corpKey));
        }
        // 未知的岗位
        else {
            dto.setErrorMessage(ResponseCodeEnum.SYSTEM_UNKNOWN_POSITION_CODE_ERROR.getMessage());
            return dto;
        }


        // 客户关键字查询
        if (StringUtils.isNotBlank(param.getKeywords())) {
            CrmCustomerQueryCloudParam customerQueryCloudParam = new CrmCustomerQueryCloudParam();
            customerQueryCloudParam.setCorpKeys(Collections.singletonList(corpKey));
            customerQueryCloudParam.setKeywords(param.getKeywords());
            CrmCustomerListCloudDto customerDtos = crmCustomerCloudService.query(customerQueryCloudParam);
            if (null != customerDtos && CollectionUtils.isNotEmpty(customerDtos.getRows())) {
                if (CollectionUtils.isEmpty(param.getCustomerKeys())) {
                    param.getCustomerKeys().addAll(customerDtos.getRows().stream().map(CrmCustomerListItemCloudDto::getCustomerPrimaryKey).collect(Collectors.toList()));
                } else {
                    // 传入的客户keys不为空的话，需要取交集
                    param.getCustomerKeys().retainAll(customerDtos.getRows().stream().map(CrmCustomerListItemCloudDto::getCustomerPrimaryKey).collect(Collectors.toList()));
                }
            } else {
                dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
                return dto;
            }
        }

        customerOrderQueryCloudParam.setCustomerOrderPrimaryKeys(param.getCustomerOrderPrimaryKeys());
        customerOrderQueryCloudParam.setCustomerKeys(param.getCustomerKeys());
        customerOrderQueryCloudParam.setCustomerNameFuzzy(param.getCustomerNameFuzzy());
        customerOrderQueryCloudParam.setServiceSectionKey(param.getServiceSectionKey());
        customerOrderQueryCloudParam.setCompletionTimeBegin(param.getCompletionTimeBegin());
        customerOrderQueryCloudParam.setCompletionTimeEnd(param.getCompletionTimeEnd());
        customerOrderQueryCloudParam.setRegistrationTimeBegin(param.getRegistrationTimeBegin());
        customerOrderQueryCloudParam.setRegistrationTimeEnd(param.getRegistrationTimeEnd());
        customerOrderQueryCloudParam.setPotentialDemandKey(param.getPotentialDemandKey());
        customerOrderQueryCloudParam.setStatuses(param.getStatuses());
        customerOrderQueryCloudParam.setPageSize(param.getPageSize());
        customerOrderQueryCloudParam.setCurrentPage(param.getCurrentPage());
        CrmCustomerOrderListCloudDto customerOrderDtos = crmCustomerOrderCloudService.query(customerOrderQueryCloudParam);
        if (null != customerOrderDtos && CollectionUtils.isNotEmpty(customerOrderDtos.getRows())) {
            // 查询客户信息
            CrmCustomerQueryCloudParam customerQueryCloudParam = new CrmCustomerQueryCloudParam();
            customerQueryCloudParam.setCustomerPrimaryKeys(customerOrderDtos.getRows().stream().map(CrmCustomerOrderListItemCloudDto::getCustomerKey).collect(Collectors.toList()));
            // customerQueryCloudParam.setCorpKeys(Collections.singletonList(corpKey));
            CrmCustomerListCloudDto customerDtos = crmCustomerCloudService.query(customerQueryCloudParam);
            Map<String, CrmCustomerListItemCloudDto> customerMap = new HashMap<>();
            if (null != customerDtos && CollectionUtils.isNotEmpty(customerDtos.getRows())) {
                customerMap.putAll(customerDtos.getRows().stream().collect(Collectors.toMap(CrmCustomerListItemCloudDto::getCustomerPrimaryKey, Function.identity(), (k1, k2) -> k1)));
            }

            List<AppletCustomerOrderListItemCloudDto> items = new ArrayList<>();
            customerOrderDtos.getRows().forEach(customerOrder -> {
                AppletCustomerOrderListItemCloudDto item = new AppletCustomerOrderListItemCloudDto();
                item.setCustomerOrderPrimaryKey(customerOrder.getCustomerOrderPrimaryKey());
                item.setCustomerKey(customerOrder.getCustomerKey());
                item.setCustomerName(customerOrder.getCustomerName());
                if (customerMap.containsKey(customerOrder.getCustomerKey())) {
                    CrmCustomerListItemCloudDto customer = customerMap.get(customerOrder.getCustomerKey());
                    item.setCustomerWechatId(customer.getWechatId());
                    item.setCustomerPhone(customer.getPhone());
                }
                item.setServiceSectionKey(customerOrder.getServiceSectionKey());
                item.setServiceSectionName(customerOrder.getServiceSectionName());
                item.setServiceItemsKey(customerOrder.getServiceItemsKey());
                item.setServiceItemsName(customerOrder.getServiceItemsName());
                item.setServiceUserKey(customerOrder.getServiceUserKey());
                item.setServiceUserName(customerOrder.getServiceUserName());
                item.setCorpKey(customerOrder.getCorpKey());
                item.setIncomeRmb(customerOrder.getIncomeRmb());
                item.setIncomeHkd(customerOrder.getIncomeHkd());
                item.setAnnexKey(customerOrder.getAnnexKey());
                item.setSourceDepartmentKey(customerOrder.getSourceDepartmentKey());
                item.setSourceDepartmentName(customerOrder.getSourceDepartmentName());
                item.setSourceUserName(customerOrder.getSourceUserName());
                item.setSourceUserKey(customerOrder.getSourceUserKey());
                item.setCompletionTime(customerOrder.getCompletionTime());
                item.setRegistrationTime(customerOrder.getRegistrationTime());
                item.setPotentialDemandKey(customerOrder.getPotentialDemandKey());
                item.setPotentialDemandName(customerOrder.getPotentialDemandName());
                item.setRemark(customerOrder.getRemark());
                item.setStatus(customerOrder.getStatus());
                item.setStatusName(YoukeyiDdyCloudBasicCrmConstant.CRM_ORDER_STATUS.getName(customerOrder.getStatus()));
                item.setIsDeleted(customerOrder.getIsDeleted());
                item.setIsDeletedName(customerOrder.getIsDeletedName());
                item.setCreateUserKey(customerOrder.getCreateUserKey());
                item.setCreateUserName(customerOrder.getCreateUserName());
                item.setCreateTime(customerOrder.getCreateTime());
                items.add(item);
            });
            dto.setRows(items);
            dto.setTotal(customerOrderDtos.getTotal());
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public AppletCustomerOrderDetailCloudDto detail(String customerOrderPrimaryKey) {
        AppletCustomerOrderDetailCloudDto dto = new AppletCustomerOrderDetailCloudDto();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            dto.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return dto;
        }
        if (StringUtils.isBlank(customerOrderPrimaryKey)) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        CrmCustomerOrderQueryCloudParam userQueryCloudParam = new CrmCustomerOrderQueryCloudParam();
        userQueryCloudParam.setCustomerOrderPrimaryKeys(Collections.singletonList(customerOrderPrimaryKey));
        CrmCustomerOrderListCloudDto customerOrderDtos = crmCustomerOrderCloudService.query(userQueryCloudParam);
        if (null != customerOrderDtos && CollectionUtils.isNotEmpty(customerOrderDtos.getRows())) {
            CrmCustomerOrderListItemCloudDto customerOrder = customerOrderDtos.getRows().get(0);

            // 查询客户信息
            CrmCustomerQueryCloudParam customerQueryCloudParam = new CrmCustomerQueryCloudParam();
            customerQueryCloudParam.setCustomerPrimaryKeys(Collections.singletonList(customerOrder.getCustomerKey()));
            // customerQueryCloudParam.setCorpKeys(Collections.singletonList(corpKey));
            CrmCustomerListCloudDto customerDtos = crmCustomerCloudService.query(customerQueryCloudParam);
            Map<String, CrmCustomerListItemCloudDto> customerMap = new HashMap<>();
            if (null != customerDtos && CollectionUtils.isNotEmpty(customerDtos.getRows())) {
                customerMap.putAll(customerDtos.getRows().stream().collect(Collectors.toMap(CrmCustomerListItemCloudDto::getCustomerPrimaryKey, Function.identity(), (k1, k2) -> k1)));
            }

            dto.setCustomerOrderPrimaryKey(customerOrder.getCustomerOrderPrimaryKey());
            dto.setCustomerKey(customerOrder.getCustomerKey());
            dto.setCustomerName(customerOrder.getCustomerName());
            if (customerMap.containsKey(customerOrder.getCustomerKey())) {
                CrmCustomerListItemCloudDto customer = customerMap.get(customerOrder.getCustomerKey());
                dto.setCustomerWechatId(customer.getWechatId());
                dto.setCustomerPhone(customer.getPhone());
            }
            dto.setServiceSectionKey(customerOrder.getServiceSectionKey());
            dto.setServiceSectionName(customerOrder.getServiceSectionName());
            dto.setServiceItemsKey(customerOrder.getServiceItemsKey());
            dto.setServiceItemsName(customerOrder.getServiceItemsName());
            dto.setServiceUserKey(customerOrder.getServiceUserKey());
            dto.setServiceUserName(customerOrder.getServiceUserName());
            dto.setIncomeRmb(customerOrder.getIncomeRmb());
            dto.setIncomeHkd(customerOrder.getIncomeHkd());
            dto.setAnnexKey(customerOrder.getAnnexKey());
            dto.setRemark(customerOrder.getRemark());
            dto.setSourceDepartmentKey(customerOrder.getSourceDepartmentKey());
            dto.setSourceDepartmentName(customerOrder.getSourceDepartmentName());
            dto.setSourceUserName(customerOrder.getSourceUserName());
            dto.setSourceUserKey(customerOrder.getSourceUserKey());
            dto.setCompletionTime(customerOrder.getCompletionTime());
            dto.setRegistrationTime(customerOrder.getRegistrationTime());
            dto.setPotentialDemandKey(customerOrder.getPotentialDemandKey());
            dto.setPotentialDemandName(customerOrder.getPotentialDemandName());
            dto.setStatus(customerOrder.getStatus());
            dto.setStatusName(YoukeyiDdyCloudBasicCrmConstant.CRM_ORDER_STATUS.getName(customerOrder.getStatus()));
            dto.setIsDeleted(customerOrder.getIsDeleted());
            dto.setIsDeletedName(customerOrder.getIsDeletedName());
            dto.setCreateUserKey(customerOrder.getCreateUserKey());
            dto.setCreateUserName(customerOrder.getCreateUserName());
            dto.setCreateTime(customerOrder.getCreateTime());
            dto.setUpdateUserKey(customerOrder.getUpdateUserKey());
            dto.setUpdateUserName(customerOrder.getUpdateUserName());
            dto.setUpdateTime(customerOrder.getUpdateTime());
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public ResponseContent create(AppletCustomerOrderCreateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            rc.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return rc;
        }
        if (null == param
                || StringUtils.isBlank(param.getCustomerKey())
        ) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }

        CrmCustomerOrderCreateCloudParam customerOrderCreateCloudParam = new CrmCustomerOrderCreateCloudParam();
        customerOrderCreateCloudParam.setCorpKey(corpKey);
        customerOrderCreateCloudParam.setFinanceCorpKey(param.getFinanceCorpKey());
        customerOrderCreateCloudParam.setCustomerKey(param.getCustomerKey());
        customerOrderCreateCloudParam.setCustomerName(param.getCustomerName());
        customerOrderCreateCloudParam.setServiceSectionKey(param.getServiceSectionKey());
        customerOrderCreateCloudParam.setServiceSectionName(param.getServiceSectionName());
        customerOrderCreateCloudParam.setServiceItemsKey(param.getServiceItemsKey());
        customerOrderCreateCloudParam.setServiceItemsName(param.getServiceItemsName());
        customerOrderCreateCloudParam.setServiceUserKey(param.getServiceUserKey());
        customerOrderCreateCloudParam.setServiceUserName(param.getServiceUserName());
        customerOrderCreateCloudParam.setIncomeRmb(param.getIncomeRmb());
        customerOrderCreateCloudParam.setIncomeHkd(param.getIncomeHkd());
        customerOrderCreateCloudParam.setAnnexKey(param.getAnnexKey());
        customerOrderCreateCloudParam.setRemark(param.getRemark());
        customerOrderCreateCloudParam.setSourceDepartmentKey(param.getSourceDepartmentKey());
        customerOrderCreateCloudParam.setSourceDepartmentName(param.getSourceDepartmentName());
        customerOrderCreateCloudParam.setSourceUserName(param.getSourceUserName());
        customerOrderCreateCloudParam.setSourceUserKey(param.getSourceUserKey());
        customerOrderCreateCloudParam.setCompletionTime(param.getCompletionTime());
        customerOrderCreateCloudParam.setRegistrationTime(param.getRegistrationTime());
        customerOrderCreateCloudParam.setPotentialDemandKey(param.getPotentialDemandKey());
        customerOrderCreateCloudParam.setPotentialDemandName(param.getPotentialDemandName());
        customerOrderCreateCloudParam.setStatus(param.getStatus());
        customerOrderCreateCloudParam.setCreateUserKey(YoukeyiSystemContext.getUserPrimaryKey());
        customerOrderCreateCloudParam.setCreateUserName(YoukeyiSystemContext.getUserName());
        return crmCustomerOrderCloudService.create(customerOrderCreateCloudParam);
    }

    @Override
    public ResponseContent update(AppletCustomerOrderUpdateCloudParam param) {
        ResponseContent rc = new ResponseContent();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            rc.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return rc;
        }
        if (null == param
                || StringUtils.isBlank(param.getCustomerOrderPrimaryKey())
        ) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }

        CrmCustomerOrderUpdateCloudParam customerOrderUpdateCloudParam = new CrmCustomerOrderUpdateCloudParam();
        customerOrderUpdateCloudParam.setCustomerOrderPrimaryKey(param.getCustomerOrderPrimaryKey());
        customerOrderUpdateCloudParam.setCorpKey(corpKey);
        customerOrderUpdateCloudParam.setFinanceCorpKey(param.getFinanceCorpKey());
        customerOrderUpdateCloudParam.setCustomerKey(param.getCustomerKey());
        customerOrderUpdateCloudParam.setCustomerName(param.getCustomerName());
        customerOrderUpdateCloudParam.setServiceSectionKey(param.getServiceSectionKey());
        customerOrderUpdateCloudParam.setServiceSectionName(param.getServiceSectionName());
        customerOrderUpdateCloudParam.setServiceItemsKey(param.getServiceItemsKey());
        customerOrderUpdateCloudParam.setServiceItemsName(param.getServiceItemsName());
        customerOrderUpdateCloudParam.setServiceUserKey(param.getServiceUserKey());
        customerOrderUpdateCloudParam.setServiceUserName(param.getServiceUserName());
        customerOrderUpdateCloudParam.setIncomeRmb(param.getIncomeRmb());
        customerOrderUpdateCloudParam.setIncomeHkd(param.getIncomeHkd());
        customerOrderUpdateCloudParam.setAnnexKey(param.getAnnexKey());
        customerOrderUpdateCloudParam.setRemark(param.getRemark());
        customerOrderUpdateCloudParam.setSourceDepartmentKey(param.getSourceDepartmentKey());
        customerOrderUpdateCloudParam.setSourceDepartmentName(param.getSourceDepartmentName());
        customerOrderUpdateCloudParam.setSourceUserName(param.getSourceUserName());
        customerOrderUpdateCloudParam.setSourceUserKey(param.getSourceUserKey());
        customerOrderUpdateCloudParam.setCompletionTime(param.getCompletionTime());
        customerOrderUpdateCloudParam.setRegistrationTime(param.getRegistrationTime());
        customerOrderUpdateCloudParam.setPotentialDemandKey(param.getPotentialDemandKey());
        customerOrderUpdateCloudParam.setPotentialDemandName(param.getPotentialDemandName());
        customerOrderUpdateCloudParam.setStatus(param.getStatus());
        customerOrderUpdateCloudParam.setUpdateUserKey(YoukeyiSystemContext.getUserPrimaryKey());
        customerOrderUpdateCloudParam.setUpdateUserName(YoukeyiSystemContext.getUserName());
        return crmCustomerOrderCloudService.update(customerOrderUpdateCloudParam);
    }

}
